package com.cskaoyan.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 创建日期: 2022/06/09 11:25
 *
 * @author ciggar
 */
public class MybatisUtils {

    static SqlSession sqlSession;

    static {

        // 1. 获取主配置文件的输入流
        //InputStream inputStream = MybatisMain.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
        InputStream stream = null;
        try {
            stream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }


        // 2. 获取SQLSessionFactoryBuilder  XxxBuilder 建造者 建造者模式，建造者模式的目的是为了去创建对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        // 3. 获取SQLSessionFactory
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(stream);

        // 4. 获取SqlSession
        sqlSession = sqlSessionFactory.openSession(true);

    }


    public static SqlSession getSqlSession() {
        return sqlSession;
    }
}
